#!/bin/bash
if [ ! $# -eq 2 ]
then
    echo "usage : configure_httpd_for_django_project.sh projectname project.virtual.host"
        exit
fi


pushd /usr/local/django/$1

if [ ! -e sqlite.db ]
then
	python2.7 manage.py syncdb
fi

chgrp apache sqlite.db .
chmod g+w sqlite.db .

# Updating wsgi.py if necessary
sed -i "s/^\(import os\)$/\1\, sys/" $1/wsgi.py
sed -i "/^import os\, sys/,/^os.environ/ s/^$/sys\.path\.append('\/usr\/local\/django')\n/" $1/wsgi.py
sed -i "/^import os\, sys/,/^os.environ/ s/^$/sys\.path\.append('\/usr\/local\/django\/$1')/" $1/wsgi.py

echo "
<VirtualHost *:80>
    ServerAdmin webmaster@$2
    ServerName $2
    ErrorLog logs/$2-error
    CustomLog logs/$2-access common

    Alias /static/ /usr/local/django/$1/static/

    <Directory /usr/local/django/$1/static>
        Order deny,allow
        Allow from all
    </Directory>
    
    Alias /media/ /usr/local/django/$1/media/

    <Directory /usr/local/django/$1/media>
        Order deny,allow
        Allow from all
    </Directory>

    WSGIScriptAlias / /usr/local/django/$1/$1/wsgi.py
</VirtualHost>" >> /etc/httpd/conf/httpd.conf

# active les hôtes virtuels nommés
sed -i "s/^#.*\(NameVirtualHost\).*\(\*\:80$\)/\1 \2/" /etc/httpd/conf/httpd.conf
ln -s /usr/local/lib/python2.7/site-packages/django/contrib/admin/static/admin/ /usr/local/django/$1/static/admin

service httpd restart
